package com.huqing.icu.service.impl;

import com.huqing.icu.base.PagingDto;
import com.huqing.icu.base.redis.annotation.RedisLock;
import com.huqing.icu.constants.CacheLockConstants;
import com.huqing.icu.dao.ChatSessionDao;
import com.huqing.icu.dto.ChatSessionQueryDto;
import com.huqing.icu.enums.DeleteStatusEnum;
import com.huqing.icu.model.ChatSession;
import com.huqing.icu.req.app.chatsession.ChatSessionHistoryMessageReq;
import com.huqing.icu.resp.app.ChatSessionHistoryMessageResp;
import com.huqing.icu.service.IChatSessionService;
import com.huqing.icu.utils.CopyUtils;
import com.huqing.icu.utils.PageUtils;
import com.huqing.icu.utils.ParamValidateUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * @Description 对话接口实现类
 * @Author huqing
 * @Date 2025/7/26 18:06
 **/
@Service
public class ChatSessionServiceImpl implements IChatSessionService {

    private static final Logger logger = LoggerFactory.getLogger(IChatSessionService.class);

    @Autowired
    private ChatSessionDao chatSessionDao;

    /**
     * 创建新对话
     *
     * @param userId
     * @param title
     * @return
     */
    @RedisLock(key = CacheLockConstants.AIPrefix.USER_CREATE_SESSION, waitTime = 3000)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long create(Long userId, String title) {

        //只取前100个字
        title = title.length() <= 100 ? title : title.substring(0, 100);

        ChatSession chatSession = new ChatSession();
        chatSession.setUserId(userId);
        chatSession.setTitle(title);
        chatSession.setIsDeleted(DeleteStatusEnum.NOT_DELETED.getCode());
        chatSessionDao.saveOrUpdate(chatSession);
        return chatSession.getId();
    }


    /**
     * 修改对话标题
     *
     * @param id
     * @param userId
     * @return
     */
    @RedisLock(key = CacheLockConstants.AIPrefix.USER_UPDATE_SESSION_TITLE, waitTime = 3000)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer updateTitle(Long id, Long userId, String title) {
        ChatSession chatSession = chatSessionDao.selectByIdAndUserId(id, userId);
        if (chatSession == null) {
            ParamValidateUtils.throwObjectNotExistExp("对话不存在，请检查");
        }
        chatSession.setTitle(title);
        chatSessionDao.saveOrUpdate(chatSession);
        return 1;
    }

    /**
     * 删除对话
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    public Integer delete(Long id, Long userId) {
        ChatSession chatSession = chatSessionDao.selectByIdAndUserId(id, userId);
        if (chatSession == null) {
            ParamValidateUtils.throwObjectNotExistExp("对话不存在，请检查");
        }
        chatSessionDao.deleteById(id, userId);
        return 1;
    }

    /**
     * 查询历史对话
     *
     * @param queryReq
     * @return
     */
    @Override
    public PagingDto<ChatSessionHistoryMessageResp> historyMessage(ChatSessionHistoryMessageReq queryReq) {
        int startIndex = PageUtils.getPageStartIndex(queryReq.getPageIndex(), queryReq.getPageSize());
        queryReq.setStartIndex(startIndex);
        Integer count = chatSessionDao.getNumByUserId(queryReq.getUserId());
        if (count == 0) {
            return new PagingDto<>(Collections.emptyList(), 0, 0);
        }
        ChatSessionQueryDto queryDto = CopyUtils.copy(queryReq, ChatSessionQueryDto.class);
        List<ChatSession> chatSessionList = chatSessionDao.selectByCondition(queryDto);
        return new PagingDto<>(chatSessionList, PageUtils.getTotalPage(count, queryReq.getPageSize()), count);

    }

    /**
     * 导出消息
     *
     * @param chatSessionId
     * @param userId
     * @param response
     */
    @Override
    public void exportMessage(Long chatSessionId, Long userId, HttpServletResponse response) {

    }
}
